package top.healthylife.gateway.platform.geo.api.util.client;


import top.healthylife.basics.utils.exception.BusinessException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Objects;

// import org.apache.commons.codec.binary.Base64;

/**
 * 适用于PHP对接时的AES加解密
 * @author wushujia
 *
 */
public class AES2 extends ByteHexStr{
    private static final String AES_TYPE = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param plainText
     * @param keyStr    16个字符
     * @return
     */
    public static String encrypt(String plainText, String keyStr) {
        byte[] encrypt ;
        try {
            Key key = generateKey(keyStr);
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encrypt = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("参数加密异常");
        }
        return  parseByte2HexStr(encrypt);
    }

    /**
     * 解密
     *
     * @param encryptData 待解密的字符串
     * @param keyStr      16个字符
     * @return 解密后的字符
     */
    public static String decrypt(String encryptData, String keyStr) {
        byte[] decrypt ;
        try {
            Key key = generateKey(keyStr);
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            decrypt = cipher.doFinal(Objects.requireNonNull(parseHexStr2Byte(encryptData)));
            return new String(decrypt, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("参数解密异常");
        }

    }

    private static Key generateKey(String key)  {
        return new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
    }

    /**
     * 将二进制转换成16进制
     *
     * @param bytes 字符数组
     * @return 16进制
     */
    public static String parseByte2HexStr(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr 16进制字符
     * @return byte[]
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}